from django.http import Http404,HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext

from bayanihan.maps.helpers import get_report_by_id, save_report_from_post_data, save_deployment_from_post_data, save_user_from_post_data, get_all_parent_deployments, get_all_child_deployments, get_all_children_from_a_parent_deployment, get_deployment_list, create_feature_collection_for_every_child_deployment, create_feature_collection_for_a_child_deployment, get_all_reports_from_a_deployment, does_this_user_own_that_deployment, validate_user, get_index_details

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.conf import settings
from couchdb import Server
import json
from StringIO import StringIO
from django.views.decorators.csrf import csrf_exempt, csrf_protect

SERVER = Server(getattr(settings,'COUCHDB_SERVER','http://127.0.0.1:5984'))
DATABASE_NAME = getattr(settings, 'COUCHDB_DATABASE_NAME', 'sample')

def view_all_reports(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    else:
        docs = SERVER[DATABASE_NAME]
        output_dictionary = {}
        deployment = {}

        username = str(request.user)
        deployment = create_feature_collection_for_every_child_deployment(username)
        deployment_list = get_deployment_list(username) 
        
        output_dictionary = {'deployments' : deployment_list, 'reports' : deployment, 'username': username}
            
        return render_to_response('home.html',
                                  output_dictionary,
                                  context_instance=RequestContext(request));
                              
def list_all_reports(request, deployment_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    else:
        docs = SERVER[DATABASE_NAME]
        username = str(request.user)
        
        deployment_list = get_deployment_list(username)
        child_deployments = get_all_child_deployments(username)
        
        if deployment_id == '':
            if child_deployments:
                deployment_id = child_deployments[0]
                return HttpResponseRedirect('/deployments/%s' % deployment_id)
            
        is_owner = does_this_user_own_that_deployment(username, deployment_id)
        if is_owner:
            reports = get_all_reports_from_a_deployment(deployment_id)
        else:
            reports = ''
            
        output_dictionary = {'deployments' : deployment_list, 'reports': reports, 'deployment_id' : deployment_id, 'username': username}
    
        return render_to_response('reports.html',
                              output_dictionary,
                              context_instance=RequestContext(request));

def view_single_report(request, report_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    else:
        docs = SERVER[DATABASE_NAME]
        username = str(request.user)
        
        view = "function(doc){if (doc._id=='%s') emit(doc._id,doc);}" % (report_id)
        report = docs.query(view)
        
        feature_collection = '{"type":"FeatureCollection","features":['
        for x in report:
            io_str = StringIO()
            json.dump(x.value, io_str)
            feature_collection = feature_collection + io_str.getvalue() + ','
        feature_collection = feature_collection[0:-1] + ']}'
        
        output_dictionary = {'report': report, 'feature':feature_collection, 'username': username}
        
        return render_to_response('detail.html',
                                  output_dictionary,
                                  context_instance=RequestContext(request));

def add_report(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    else:
        username = str(request.user)
        if request.method == "POST":
            report_id = save_report_from_post_data(request.POST, username)
            return HttpResponseRedirect(u"/reports/%s/" % report_id)
        else:
            deployment_list = get_deployment_list(username)
            child_deployments = get_all_child_deployments(username)
                        
            output_dictionary = {'deployments': child_deployments, 'username': username}
            
            return render_to_response('submit.html', 
                                  output_dictionary,
                                  context_instance=RequestContext(request));
def test(request):
    if request.is_ajax():
        if request.method == 'GET':
            deployment_id = request.GET['deployment_id']
            
            if(deployment_id):
                index_details = get_index_details(deployment_id)
                index_details = json.dumps(index_details)
                return HttpResponse(index_details)
                                  
def create_deployment(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    else:
        username = str(request.user)
        if request.method == "POST":
            save_deployment_from_post_data(request.POST, username)
            return HttpResponseRedirect(u"/submit/")
        else:
            deployment_list = get_deployment_list(username)
            parent_deployments = [] 
            for parent in deployment_list:
                parent_deployments.append(parent)

            output_dictionary = {'deployments': parent_deployments, 'username': username, 'username': username}
            
            return render_to_response('creation/deploy.html', 
                                      output_dictionary,
                                      context_instance=RequestContext(request))

def sign_in(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                request.session['username'] = username
                login(request, user)
                return HttpResponseRedirect('/');
        else:
            output_dictionary = {'error_message' : 'Incorrect username or password', 'username' : username}
            return render_to_response('users/login.html', output_dictionary,context_instance=RequestContext(request));
    else:
        return render_to_response('users/login.html', context_instance=RequestContext(request));
        
def register(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        save_user_from_post_data(request.POST)

        try:
            user = User.objects.create_user(username, email, password)
        except IntegrityError:
            output_dictionary = {'error_message' : 'Username is already taken.', 'username' : username, 'email' : email}
            return render_to_response('users/register.html', output_dictionary,context_instance=RequestContext(request));
        
        user = authenticate(username=username, password=password)
        login(request, user)
        return HttpResponseRedirect('/');    
        
    else:
        return render_to_response('users/register.html', context_instance=RequestContext(request));

def sign_out(request):
    logout(request)
    return HttpResponseRedirect('/login/');               

#DASHBOARD  
def view_account(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    else:
        username = str(request.user)
        output_dictionary = {'username': username}
        
        return render_to_response('dashboard/account.html',
                              output_dictionary,
                              context_instance=RequestContext(request));
                              
def view_members(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)
    else:
        username = str(request.user)
        output_dictionary = {'username': username}
        
        return render_to_response('dashboard/members.html',
                              output_dictionary,
                              context_instance=RequestContext(request));